package com.example.etwzgzxt.tool;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.client.utils.URLEncodedUtils;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.protocol.HTTP;

/**
 * Created by 创宇 on 2016/4/28.
 */
public class HttpHelper {

    public String get(String baseUrl, List<NameValuePair> pairList) {
        try {
            String param = URLEncodedUtils.format(pairList, "UTF-8");
            HttpGet httpGet = new HttpGet(baseUrl + "?" + param);//将URL与参数拼接
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpGet);
            return showResponseResult(response);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String post(String baseUrl, List<NameValuePair> pairList) {
        try {
            HttpEntity requestHttpEntity = new UrlEncodedFormEntity(pairList, HTTP.UTF_8);
            HttpPost httpPost = new HttpPost(baseUrl);
            httpPost.setEntity(requestHttpEntity);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpPost);
            return showResponseResult(response);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String showResponseResult(HttpResponse response)
    {
        if (null == response) {
            return null;
        }
        HttpEntity httpEntity = response.getEntity();
        try {
            InputStream inputStream = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream));
            String result = "";
            String line = "";
            while (null != (line = reader.readLine())) {
                result += line;
            }
            System.out.println(result);
            return result;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
